<?php

namespace App\Web\Model;

use EchoPHP\Facades\Db;
use EchoPHP\Validator\Validator;
use App\Web\Model\User as UserModel;
use App\Web\Model\Team as TeamModel;
use App\Web\Model\Login as LoginModel;

/**
 * Class Member
 * 团队成员管理相关业务逻辑
 * @package App\Web\Model
 */
class Member extends Model {
    /**
     * 获取团队成员列表数量统计
     */
    public function getMemberListCount($search = [], $teamCode = null) {
        $field = 'count(1) as count';
        $search['issuper'] = 0;
        //使用UserModel中的搜索方法
        $userModel = new UserModel();
        return $userModel->search($field, $search, 0, 0, '', $teamCode)[0]['count'];
    }

    /**
     *获取团队成员列表
     */
    public function getMemberList($search = [], $rowFrom = 0, $rowTo = 0, $teamCode = null) {
        $field = 'userid,username,cname,User.teamid,teamrole,islock,User.teamcode,leader,Team.teamname';
        $search['issuper'] = 0;
        //使用UserModel中的搜索方法
        $userModel = new UserModel();
        $userList = $userModel->search($field, $search, $rowFrom, $rowTo, 'userid ASC', $teamCode, false, true);

        return ['status' => true, 'message' => '获取成功', 'memberList' => $userList];
    }

    /**
     * 保存团队成员信息，修改或者新增
     * @param $userId
     * @param $teamCode
     * @param $teamRole
     * @param $leader
     * @return array
     * @throws \Exception
     */
    public function saveMemberInfo($userId, $teamCode, $teamRole, $leader) {
        //角色必须设置
        $rule = [
            'userid|用户id' => [
                'required', 'number'
            ],
            'teamcode|团队code' => [
                'required'
            ],
            'teamrole|团队身份' => [
                'required', 'in' => '1,2'
            ],
            'leader|领导' => [
                'required'
            ],
        ];
        $msg = [
            'teamrole.in' => '请选择团队身份',
            'teamid' => '请选择所属团队'
        ];

        $validate = new Validator($rule, $msg);
        $result = $validate->validate([
            'userid' => $userId,
            'teamcode' => $teamCode,
            'teamrole' => $teamRole,
            'leader' => $leader
        ]);
        if (!$result) {
            return ['status' => false, 'message' => '执行失败', 'errorFields' => $validate->getErrors()];
        }

        //检测团队是否有效
        $teamModel = new TeamModel();
        $teamInfo = $teamModel->getTeamInfoByCode($teamCode, 'teamid,teamcode');

        if (empty($teamInfo)) {
            return ['status' => false, 'message' => '执行失败', 'errorFields' => ['teamid' => '团队不存在']];
        }

        //校验上级leader信息
        $userModel = new UserModel();
        $leaderInfo = $userModel->getInfo($leader, 'cname,teamcode,teamrole,issuper');
        if (empty($leaderInfo)) {
            return ['status' => false, 'message' => '字段校验失败', 'errorFields' => ['leader' => '请选择上级领导']];
        }

        if ($leaderInfo['issuper'] != 1 && (substr($leaderInfo['teamcode'], 0, 5) != substr($teamInfo['teamcode'], 0, 5) || $leaderInfo['teamrole'] != 2)) {
            return ['status' => false, 'message' => '字段校验失败', 'errorFields' => ['leader' => '所选领导不是当前团队的leader']];
        }

        $sql = 'UPDATE User SET teamid=?,teamcode=?,teamrole=?,leader=?,leadername=?,updatedate=now() WHERE userid=? AND issuper=?';
        $var = [$teamInfo['teamid'], $teamInfo['teamcode'], $teamRole, $leader, $leaderInfo['cname'], $userId, 0];
        $saveResult = Db::update($sql, $var);

        if (!$saveResult) {
            return ['status' => false, 'message' => '执行失败'];
        }

        $loginModel = new LoginModel();
        $loginModel->excluded(0, $userId, '您的账号已被修改，请重新登录');
        return ['status' => true, 'message' => '执行成功'];
    }

    /**
     * 根据团队成员id删除团队成员，有关联用户不可删除改团队成员
     * @param $userId
     * @return array
     */
    public function removeMember($oprId, $userId) {
        //检测团队成员id
        if ($userId <= 0) {
            return ['status' => false, 'message' => '请传入正确的成员id'];
        }
        $userModel = new UserModel();
        $superAdmin = $userModel->search('userid,cname', ['issuper' => 1]);

        if (empty($superAdmin)) {
            return ['status' => false, 'message' => '删除团队成员失败'];
        }

        $sql = 'UPDATE User SET teamid=?,teamcode=?,teamrole=?,leader=?,leadername=?,updatedate=now() WHERE userid=?';
        $var = [1, '00000', '1', $superAdmin[0]['userid'], $superAdmin[0]['cname'], $userId];
        $result = Db::update($sql, $var);
        if ($result) {
            $loginModel = new LoginModel();
            $loginModel->excluded($oprId, $userId, '您已被移出团队，请重新登录');
            return ['status' => true, 'message' => '删除团队成员成功'];
        }
        return ['status' => false, 'message' => '删除团队成员失败'];
    }

    /**
     * 验证一个用户是否是另一个用户的下属成员
     * @param $userId
     * @param $teamCode
     * @return bool
     */
    public function chkIsMember($userId, $teamCode) {
        $sql = 'select count(1) as count from `User` WHERE userid=? AND teamcode LIKE ? AND `status`=?';
        $var = [$userId, $teamCode . '%', '01'];

        $result = Db::selectOne($sql, $var);
        return $result['count'] > 0 ? true : false;
    }

}